package P3排序算法;

import java.util.Arrays;

//单路快速排序
public class QuickSort01 {
    public static void main(String[] args) {
        int[] arr = {9, 1, 8, 2, 7, 3, 6, 4, 5};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public static void quickSort(int[] arr, int l, int r) {
        if (l >= r) {
            return;
        }
        int p = partition(arr, l, r);
        quickSort(arr, l, p - 1);
        quickSort(arr, p + 1, r);
    }

    private static int partition(int[] arr, int l, int r) {
        //为了避免极端递增或递减 导致二叉树退化成链表
        //采取随机值的情况 让后续随机一个元素当关键字
        //[10] 0~9      6~12
        swap(arr, l, (int) (Math.random() * (r - l + 1) + l));
        int v = arr[l];
        int j = l;  //[l+1,j] <= v   [j+1,i-1] > v
        for (int i = l + 1; i <= r; i++) {
            if (arr[i] <= v) {
                swap(arr, j + 1, i);
                j++;
            }
        }
        swap(arr, l, j);
        return j;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}